﻿using Microsoft.Office.InfoPath;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace InfoPathHelpers
{
    public class FileDataSourceContext : DataSourceContext
    {
        private FileInfo _DataSourceFile;

        public FileDataSourceContext(DataSource dataSource) 
            : base(dataSource) 
        {
            Initialize();
        }

        public FileDataSourceContext(DataSource dataSource, IXmlNamespaceResolver namespaceManager) 
            : base(dataSource, namespaceManager) 
        {
            Initialize();
        }

        public FileDataSourceContext(XmlFormHostItem form, string dataSourceName)
            : base(form.DataSources[dataSourceName]) 
        {
            Initialize();
        }

        private void Initialize()
        {
            var QueryConnection = _DataSource.QueryConnection as FileQueryConnection;
            _DataSourceFile = new FileInfo(QueryConnection == null ? "" : QueryConnection.FileLocation);
        }

        public string FileLocation
        {
            get 
            {
                return _DataSourceFile.FullName;
            }
        }

        public bool Exists
        {
            get { return _DataSourceFile.Exists; }
        }

        public void Save()
        {
            XmlDocument Document = new XmlDocument();
            Document.Load(_DataSourceFile.FullName);
            using(XmlReader Reader = _DataSource.CreateNavigator().SelectSingleNode("/*", NamespaceManager).ReadSubtree())
            {
                Document.CreateNavigator().SelectSingleNode("/*").ReplaceSelf(Reader);
            }
            Document.Save(_DataSourceFile.FullName);
        }
    }
}
